package com.yueqian.framework.config;


import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.*;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

@Configuration
@EnableCaching
public class RedisConfig {
	private final RedisConnectionFactory redisConnectionFactory;

	@Autowired
	public RedisConfig(RedisConnectionFactory redisConnectionFactory) {
		this.redisConnectionFactory = redisConnectionFactory;
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		StringRedisTemplate redisTemplate = new StringRedisTemplate();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(stringRedisSerializer);
		return redisTemplate;
	}


	@Bean
	public DefaultRedisScript<Long> limitScript() {
		DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
		redisScript.setScriptText(limitScriptText());
		redisScript.setResultType(Long.class);
		return redisScript;
	}

	@Bean
	public CacheManager cacheManager() {
		// 初始化一个 RedisCacheWriter
		// RedisCacheWriter 提供了对 Redis 的 set、setnx、get 等命令的访问权限
		// 可以由多个缓存实现共享,并负责写/读来自 Redis 的二进制数据
		RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

		// 设置 CacheManager 的值序列化方式
		GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer();
		RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
																		   .fromSerializer(jsonSerializer);
		// 提供 Redis 的配置
		RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
															 .entryTtl(Duration.ofMinutes(10))
															 .disableCachingNullValues()
															 .serializeValuesWith(pair);

		// 默认配置（强烈建议配置上）。  比如动态创建出来的都会走此默认配置
		RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
													  .cacheDefaults(defaultCacheConfig)
													  .build();

		// 初始化 RedisCacheManager 返回
		return redisCacheManager;
	}


	/**
	 * 37      * 配置Jackson2JsonRedisSerializer序列化策略
	 * 38      *
	 */
	private Jackson2JsonRedisSerializer<Object> serializer() {
		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();

		// 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

		// 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
		objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);


		objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		return jackson2JsonRedisSerializer;
	}


	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		// 用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
		redisTemplate.setValueSerializer(serializer());

		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		// 使用StringRedisSerializer来序列化和反序列化redis的key值
		redisTemplate.setKeySerializer(stringRedisSerializer);

		// hash的key也采用String的序列化方式
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		// hash的value序列化方式采用jackson
		redisTemplate.setHashValueSerializer(serializer());
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}


	@Bean
	public CacheManager cacheManager(RedisConnectionFactory factory) {
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
// 配置序列化（解决乱码的问题）
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

												 // 使用StringRedisSerializer来序列化和反序列化redis的key值
												 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
												 // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
												 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer()))
												 // 禁用空值
												 .disableCachingNullValues();

		return RedisCacheManager.builder(factory)
					   .cacheDefaults(config)
					   .build();
		     }

	/**
	 * 限流脚本.
	 */
	private String limitScriptText() {
		return "local key = KEYS[1]\n"
					   + "local count = tonumber(ARGV[1])\n"
					   + "local time = tonumber(ARGV[2])\n"
					   + "local current = redis.call('get', key);\n"
					   + "if current and tonumber(current) > count then\n"
					   + "    return tonumber(current);\n"
					   + "end\n"
					   + "current = redis.call('incr', key)\n"
					   + "if tonumber(current) == 1 then\n"
					   + "    redis.call('expire', key, time)\n"
					   + "end\n"
					   + "return tonumber(current);";
	}
}
